#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: LiangChao
@email：kevinleong1011@hotmail.com

@desc: 
"""
import re

from makitest.grammar.errors import InvalidSentenceError


def convert_pattern_into_pattern(fmt: str):
    arg_pattern = r'\$\{[a-zA-Z_]+\}'
    matches = re.findall(arg_pattern, fmt)
    pattern = fmt
    for match in matches:
        replace_str = match.replace('${', '(?P<').replace('}', '>.+)')
        arg_name = match[2:-2]
        pattern = pattern.replace(match, replace_str)

    return pattern


class Keyword:
    """
    Keyword is to describe a api in custom grammar format.
    So you can write script with the grammar defined
    by deco "@manager.grammar('keyword name', 'grammar format')."

    Usage:
        @manager.grammar('发送信号', '发送信号 ${message}')\n
        def send(message):
            print(message)
    """

    def __init__(self, func, fmt):
        self.func = func
        self.format = fmt
        self.pattern = convert_pattern_into_pattern(fmt)

    def run(self, sentence):
        """
        Run grammar sentence
        :param sentence: sentence to be run
        :return:
        """
        args = self.parse_args(sentence)
        return self.func(**args)

    def parse_args(self, sentence):
        """
        Parse args from sentence by the pattern the keyword.
        :param sentence: grammar sentence to run
        :return:
        """
        match = re.match(self.pattern, sentence)
        if match:
            return match.groupdict()
        raise InvalidSentenceError(self.format, sentence)
